<template>
	<view class="platform-assign-container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">分配平台</text>
		</view>
		
		<!-- 账号基本信息区域 -->
		<view class="account-info-section">
			<view class="section-title">账号基本信息</view>
			<view class="info-content">
				<view class="info-item">
					<view class="info-label">用户名</view>
					<view class="info-value">{{ account_data.username || '-' }}</view>
				</view>
				<view class="info-item">
					<view class="info-label">账号ID</view>
					<view class="info-value account-id">
						{{ account_data.account_id || '-' }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 平台列表区域 -->
		<view class="platform-section">
			<view class="section-title">可分配平台</view>
			<!-- 搜索输入框 -->
			<view class="search-container">
				<view class="search-input-wrapper">
					<view class="search-icon">
						<u-icon name="search" size="40rpx" color="#999999"></u-icon>
					</view>
					<input
						type="text"
						v-model="searchQuery"
						placeholder="搜索平台名称、ID或描述"
						class="search-input"
						placeholder-style="color: #999999"
					/>
					<text
						v-if="searchQuery"
						class="clear-icon"
						@click="searchQuery = ''"
					>✕</text>
				</view>
			</view>
			<view class="info-content">
				<!-- 加载状态 -->
				<view v-if="loading_platform" class="loading-state">
					<u-loading></u-loading>
					<text style="margin-left: 20rpx; font-size: 28rpx; color: #666666;">正在获取平台信息...</text>
				</view>
				
				<!-- 错误状态 -->
				<view v-else-if="platform_error" class="error-state">
					<text style="font-size: 28rpx; color: #ff6b6b;">{{ platform_error }}</text>
					<u-button 
						style="margin-top: 20rpx;" 
						type="primary" 
					size="mini" 
					@click="fetchAllPlatforms()"
				>重新加载</u-button>
				</view>
				
				<!-- 无数据状态 -->
					<view v-else-if="platform_loaded && searchResults.length === 0" class="empty-state">
						<view class="empty-content">
							<!-- 图标 -->
							<view class="empty-icon">
								<u-icon name="search" size="80rpx" color="#999999"></u-icon>
							</view>
							<!-- 提示文本 -->
							<text class="empty-title">{{ searchQuery ? '未找到匹配的平台' : '暂无可用平台' }}</text>
							<text class="empty-subtitle">
								{{ searchQuery ? '请尝试使用不同的关键词进行搜索' : '当前没有可分配的平台' }}
							</text>
							<!-- 清空搜索按钮 -->
							<button 
								v-if="searchQuery" 
								class="clear-search-btn" 
								@tap="searchQuery = ''"
							>
								清空搜索
							</button>
						</view>
					</view>
				
				<!-- 平台列表 -->
				<view v-else class="platform-list">
					<!-- 平台统计信息 -->
					<view class="platform-stats" v-if="platform_loaded && searchResults.length > 0">
						<text style="font-size: 26rpx; color: #666666;">
							共 {{ searchResults.length }} 个平台
						</text>
					</view>
					
					<view v-for="(platform, index) in searchResults" :key="platform.platform_id || index" class="platform-item platform-item-hover">
						<view class="platform-header">
							<view style="display: flex; align-items: center; flex: 1;">
								<!-- 平台Logo -->
								<view v-if="platform.logo" class="platform-logo">
									<u-image 
										fade 
										duration="450" 
										mode="aspectFit" 
										:src="platform.logo" 
										style="width: 60rpx; height: 60rpx; border-radius: 12rpx;"
									>
										<template #error>
											<view style="width: 60rpx; height: 60rpx; background-color: #f0f0f0; border-radius: 12rpx;"></view>
										</template>
									</u-image>
								</view>
								<!-- 平台名称 -->
							<view class="platform-name" style="margin-left: 16rpx;" v-html="platform.highlighted ? platform.highlightedName : (platform.platform_name || '-')"></view>
							</view>
							<!-- 平台状态 -->
							<view class="platform-status" :class="getPlatformStatusClass(platform.status?.code)">
								{{ platform.status?.message || '-' }}
							</view>
						</view>
						<view class="platform-info">
							<view class="platform-info-item">
								<text class="platform-info-label">平台ID：</text>
								<text class="platform-info-value">
									{{ platform.platform_id || '-' }}
								</text>
							</view>
							<!-- 平台描述 -->
							<view v-if="platform.description && platform.description.trim()" class="platform-info-item">
								<text class="platform-info-label">平台描述：</text>
								<text class="platform-info-value" v-html="platform.highlighted ? platform.highlightedDescription : platform.description.trim()">
								</text>
							</view>
							<!-- 网站链接 -->
							<view v-if="platform.website && platform.website.trim()" class="platform-info-item" >
								<text class="platform-info-label">官方网站：</text>
								<text class="platform-info-value platform-website" @click="copyToClipboard(platform.website)">
									{{ platform.website }}
								</text>
							</view>
						</view>
						<!-- 操作按钮 -->
						<view class="platform-actions">
							<u-button type="primary" size="mini" @click="assignPlatformToAccount(platform)">分配平台</u-button>
						</view>
					</view>
				</view>
			</view>
		</view>
	<u-toast ref="uToastRef" />
	</view>
</template>

<script setup>
	import { ref, onMounted, watch } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { getImagePath, copyToClipboard } from '@/static/js/hub';
	import { SERVER_BASE_URL,searchAccount, get_registered_platforms, updateAccount, update_platform_real_name, get_all_platforms, register_account_to_platform } from '@/static/apis/wzry';

	// 响应式数据
	const account_data = ref({});
	// 平台数据相关响应式变量
	const platforms_data = ref([]);
	const loading_platform = ref(false);
	const platform_error = ref('');
	const platform_loaded = ref(false);
	const uToastRef = ref(null);
	const loading = ref(false);
	// 搜索相关变量
	const searchQuery = ref('');
	const searchResults = ref([]);
	
	// 高亮关键词函数
	/**
	 * 高亮文本中的关键词
	 * @param {string} text - 原始文本
	 * @param {string} keyword - 关键词
	 * @returns {string} 高亮后的HTML文本
	 */
	const highlightKeyword = (text, keyword) => {
		if (!text || !keyword || keyword.trim() === '') {
			return text;
		}
		
		const lowerText = text.toLowerCase();
		const lowerKeyword = keyword.toLowerCase();
		const keywordIndex = lowerText.indexOf(lowerKeyword);
		
		if (keywordIndex === -1) {
			return text;
		}
		
		// 截取关键词前后的文本
		const beforeKeyword = text.substring(0, keywordIndex);
		const highlightedText = text.substring(keywordIndex, keywordIndex + keyword.length);
		const afterKeyword = text.substring(keywordIndex + keyword.length);
		
		// 递归处理剩余文本，支持多个匹配
		return beforeKeyword + `<span class="highlight">${highlightedText}</span>` + 
				   highlightKeyword(afterKeyword, keyword);
	};
	
	// 执行模糊搜索
	/**
	 * 根据关键词进行本地模糊搜索
	 * @param {string} query - 搜索关键词
	 */
	const performSearch = (query) => {
		// 使用setTimeout将搜索操作放入下一个事件循环，避免阻塞UI
		setTimeout(() => {
			if (!query || query.trim() === '') {
				// 如果搜索框为空，显示所有平台
				searchResults.value = platforms_data.value.map(platform => ({
					...platform,
					highlighted: false
				}));
				return;
			}
			
			const trimmedQuery = query.trim();
			const lowerQuery = trimmedQuery.toLowerCase();
			
			// 过滤匹配的平台并添加高亮标记
			const results = platforms_data.value.filter(platform => {
				// 搜索平台名称
				if (platform.platform_name && platform.platform_name.toLowerCase().includes(lowerQuery)) {
					return true;
				}
				// 搜索平台ID
				if (platform.platform_id && platform.platform_id.toLowerCase().includes(lowerQuery)) {
					return true;
				}
				// 搜索平台描述
				if (platform.description && platform.description.toLowerCase().includes(lowerQuery)) {
					return true;
				}
				// 搜索平台网站
				if (platform.website && platform.website.toLowerCase().includes(lowerQuery)) {
					return true;
				}
				return false;
			}).map(platform => ({
				...platform,
				highlighted: true,
				query: trimmedQuery,
				// 预处理高亮后的文本
				highlightedName: highlightKeyword(platform.platform_name, trimmedQuery),
				highlightedDescription: highlightKeyword(platform.description || '', trimmedQuery),
				highlightedWebsite: highlightKeyword(platform.website || '', trimmedQuery)
			}));
			
			searchResults.value = results;
		}, 0);
	};
	
	// 监听搜索关键词变化
	watch(searchQuery, (newQuery) => {
		performSearch(newQuery);
	}, { immediate: true });
	
	// 生命周期钩子
	onLoad(async (options) => {
		try {
			
			// 请求数据
			var account = await searchAccount({
				keyword: options.account_id
			});
			if (account.code != 0) {
				uni.showToast({
					title: account.message,
					icon: 'none'
				});
				return;
			}
			
			// 安全地解析JSON数据
			account_data.value = account.data[0];
			// 获取所有平台数据
			fetchAllPlatforms();
		} catch (error) {
			console.error('解析账号数据失败:', error);
			platform_error.value = '账号数据解析失败';
		}
	});

	onMounted(() => {
		console.log('账号数据:', account_data.value);
	});
	
	// 获取所有平台数据的函数
	/**
	 * 获取并处理所有平台数据
	 * @param {number} retryCount - 当前重试次数
	 * @param {number} maxRetries - 最大重试次数
	 */
	const fetchAllPlatforms = async (retryCount = 0, maxRetries = 2) => {
		// 设置加载状态
		loading_platform.value = true;
		platform_error.value = '';
		
		try {
			// 添加超时处理
			const timeoutPromise = new Promise((_, reject) => {
				setTimeout(() => reject(new Error('请求超时，请检查网络连接')), 10000);
			});
			
			// 使用Promise.race处理超时
			const response = await Promise.race([
				get_all_platforms(),
				timeoutPromise
			]);
			
			// 检查响应是否存在
			if (!response) {
				throw new Error('服务器未返回响应数据');
			}
			
			// 检查响应格式
			if (typeof response !== 'object') {
				throw new Error('服务器返回格式错误');
			}
			
			// 检查状态码
			if (response.code === 0) {
				// 检查数据是否存在且为数组
				if (!Array.isArray(response.data)) {
					platforms_data.value = [];
					console.warn('响应成功但数据格式不正确');
				} else {
					// 转换数据结构以适应现有的展示逻辑
					platforms_data.value = response.data.map(p => ({
						platform_id: p.platform_id,
						platform_name: p.name,
						status: p.status,
						create_time: p.create_time,
						update_time: p.update_time,
						logo: p.logo ? p.logo.trim() : '',
						website: p.website ? p.website.trim() : '',
						description: p.description || ''
					})).filter(Boolean); // 过滤掉空值
					
					console.log('平台数据处理完成:', platforms_data.value);
				}
			} else {
				// 根据错误码给出不同的提示
				const errorMessage = response.message || `请求失败，错误码: ${response.code}`;
				throw new Error(errorMessage);
			}
		} catch (error) {
			console.error('获取平台数据出错:', error);
			platform_error.value = error.message || '获取平台数据时发生错误';
			
			// 重试逻辑
			if (retryCount < maxRetries && error.message !== '账号ID不存在，无法获取平台信息') {
				retryCount++;
				console.log(`第${retryCount}次重试获取平台数据...`);
				
				// 延迟重试
				await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
				return fetchAllPlatforms(retryCount, maxRetries);
			}
			
		
		} finally {
			// 更新加载状态
			loading_platform.value = false;
			platform_loaded.value = true;
			// 数据加载完成后初始化搜索结果
			performSearch(searchQuery.value);
		}
	};


	// 分配平台给账号
	/**
	 * 将平台分配给指定账号
	 * @param {Object} platform - 平台对象
	 */
	const assignPlatformToAccount = async (platform) => {
		if (!account_data.value.account_id) {
			uToastRef.value.show({
				message: '账号信息不完整，无法分配平台',
				type: 'error',
				duration: 2000
			});
			return;
		}
		
		try {
			loading.value = true;
			
			// 调用注册平台API
			const response = await register_account_to_platform({
				account_id: account_data.value.account_id,
				platform_id: platform.platform_id
			});
			
			// 检查响应状态
			if (response.code === 0) {
				uToastRef.value.show({
					title: response.message || '平台分配成功',
					type: 'primary',
					duration: 2000
				});
				
				// 返回上一页
				// setTimeout(() => {
				// 	uni.navigateBack();
				// }, 1500);
			} else {
				uToastRef.value.show({
					title: response.message || '平台分配失败',
					type: 'error',
					duration: 2000
				});
			}
		} catch (error) {
			console.error('平台分配失败:', error);
			if(uToastRef.value) {
				uToastRef.value.show({
				title: error.message || '平台分配失败，请稍后重试',
				type: 'error',
				duration: 2000
			});
			}else [
				uni.showToast({
					title: error.message || '平台分配失败，请稍后重试',
					type: 'error',
					duration: 2000
				})
			]
		} finally {
			loading.value = false;
		}
	};
	
	// 获取平台状态样式类
	/**
	 * 根据状态码返回对应的样式类
	 * @param {number} statusCode - 状态码
	 * @returns {string} 样式类名
	 */
	const getPlatformStatusClass = (statusCode) => {
		if (statusCode === 1) return 'platform-status-active';
		if (statusCode === 0) return 'platform-status-disabled';
		return 'platform-status-other';
	};
</script>

<style scoped lang="scss">
	// 主容器样式
	.platform-assign-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 页面标题样式
	.page-header {
		background-color: #ffffff;
		padding: 30rpx 40rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
	}
	
	// 信息区域通用样式
	.account-info-section,
	.platform-section {
		background-color: #ffffff;
		border-radius: 12rpx;
		padding: 30rpx 40rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	// 搜索框样式
	.search-container {
		margin-bottom: 20rpx;
	}
	
	.search-input-wrapper {
		display: flex;
		align-items: center;
		background-color: #f5f7fa;
		border-radius: 8rpx;
		padding: 0 20rpx;
		height: 72rpx;
	}
	
	.search-icon {
		font-size: 32rpx;
		color: #909399;
		margin-right: 12rpx;
	}
	
	.search-input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
		color: #303133;
		background-color: transparent;
	}
	
	.clear-icon {
		font-size: 24rpx;
		color: #909399;
		padding: 8rpx;
		border-radius: 50%;
		background-color: #e4e7ed;
	}
	
	.clear-icon:active {
		background-color: #dcdfe6;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 20rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #eeeeee;
	}
	
	// 信息内容区域
	.info-content {
		width: 100%;
	}
	
	// 信息项样式
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.info-item:last-child {
		border-bottom: none;
	}
	
	.info-label {
		font-size: 28rpx;
		color: #666666;
		flex: 1;
	}
	
	.info-value {
		font-size: 28rpx;
		color: #333333;
		flex: 2;
		text-align: right;
		word-break: break-all;
	}
	
	// 账号ID样式
	.account-id {
		font-size: 26rpx;
		color: #888888;
	}
	
	// 加载状态样式
	.loading-state {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
	}
	
	// 错误状态样式
	.error-state {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
	}
	
	// 无数据状态样式
	.empty-state {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		width: 100%;
	}
	
	.empty-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 20rpx;
	}
	
	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
		opacity: 0.7;
	}
	
	.empty-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 8rpx;
	}
	
	.empty-subtitle {
		font-size: 28rpx;
		color: #999999;
		line-height: 1.5;
		max-width: 70%;
		text-align: center;
	}
	
	.clear-search-btn {
		margin-top: 20rpx;
		background-color: #1976d2;
		color: white;
		border-radius: 30rpx;
		padding: 12rpx 40rpx;
		font-size: 28rpx;
		border: none;
	}
	
	.clear-search-btn:active {
		background-color: #1565c0;
		opacity: 0.8;
	}
	
	// 平台列表样式
	.platform-list {
		width: 100%;
		margin-top: 20rpx;
	}
	
	// 平台统计信息
	.platform-stats {
		margin-bottom: 20rpx;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	// 平台项样式
	.platform-item {
		border: 1rpx solid #f0f0f0;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		background-color: #fafafa;
		transition: background-color 0.2s, transform 0.3s ease;
	}
	
	.platform-item:last-child {
		margin-bottom: 0;
	}
	
	// 平台头部样式
	.platform-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	// 平台Logo样式
	.platform-logo {
		width: 80rpx;
		height: 80rpx;
		flex-shrink: 0;
		border-radius: 10rpx;
		object-fit: contain;
		background-color: #f5f7fa;
	}
	
	// 平台名称样式
	.platform-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #303133;
		flex: 1;
		margin-bottom: 8rpx;
	}
	
	// 高亮样式
	:deep(.highlight) {
		background-color: #FFE799;
		color: #333333;
		padding: 2rpx 0;
		font-weight: 600;
	}
	
	// 平台状态样式
	.platform-status {
		padding: 6rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		flex-shrink: 0;
		margin-bottom: 10rpx;
	}
	
	.platform-status-active, .status-1 {
		background-color: #e8f5e8;
		color: #67C23A;
	}
	
	.platform-status-disabled {
		background-color: #ffebee;
		color: #F56C6C;
	}
	
	.platform-status-other {
		background-color: #f5f5f5;
		color: #757575;
	}
	
	// 平台信息样式
	.platform-info {
		margin-bottom: 20rpx;
	}
	
	// 平台信息项样式
	.platform-info-item {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}
	
	.platform-info-item:last-child {
		margin-bottom: 0;
	}
	
	// 平台信息标签样式
	.platform-info-label {
		font-size: 26rpx;
		color: #666666;
		margin-right: 12rpx;
		width: 120rpx;
	}
	
	// 平台信息值样式
	.platform-info-value {
		font-size: 26rpx;
		color: #333333;
		flex: 1;
		word-break: break-all;
	}
	
	// 平台描述样式
	.platform-info-value {
		font-size: 26rpx;
		color: #606266;
		line-height: 1.4;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	// 平台网站样式优化
	.platform-website {
		color: #409EFF;
		text-decoration: underline;
		cursor: pointer;
		font-size: 24rpx;
		max-width: 400rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.platform-website:active {
		opacity: 0.7;
	}
	
	// 平台操作按钮样式
	.platform-actions {
		display: flex;
		justify-content: flex-end;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
	}
	
	// 平台项交互效果增强
	.platform-item-hover {
		transition: all 0.3s ease;
	}
	
	.platform-item-hover:active {
		background-color: #f5f7fa;
		transform: scale(0.98);
	}
	
	// 按钮样式优化
	.assign-button {
		animation: pulse 2s infinite;
	}
	
	@keyframes pulse {
		0% {
			box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
		}
		70% {
			box-shadow: 0 0 0 10rpx rgba(64, 158, 255, 0);
		}
		100% {
			box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
		}
	}
</style>
